package ;

import flixel.FlxBasic;
import flixel.FlxG;
import flixel.group.FlxGroup;
import flixel.group.FlxTypedGroup;
import flixel.tweens.FlxTween;
import flixel.util.FlxPoint;

/**
 * ...
 * @author LF
 */
class ItemLayer extends FlxGroup
{
	// This layer handles everything to do with item storage, movement,
	// and combination.
	
	// It holds the inventory
	private var _inv:Inventory;
	// Any item the player is currently dragging
	private var _draggedItem:Item;
    // The one slot the player can use to grow the tree
    //private var _growSlot:ItemHolder;
	// And all the combination slots
	private var _treeSegments:FlxTypedGroup<TreeSegmentSlots>;
	
	// Some other stuff to keep track of
	// Is an item currently being dragged?
	private var _dragging:Bool;
	// The offset between the mouse and the item being dragged
	private var _mouseOffset:FlxPoint;
	// The place this item started the drag
	private var _dragStart:FlxPoint;
	// Whether the dragged item should scroll the screen yet
	private var _dragScroll:Bool;
    // How much the player has to feed the tree before it grows a new segment
    //private var _growHere:Int;
    // How much the player has already fed the tree
    //private var _currentScore:Int;
    
    // Stuff for communicating with PlayState
    private var _spawnNewSegment:Bool;
    private var _newSegmentGraphic:String;
    
    // temp use
    private var segNum:Int;

	public function new() 
	{
		super();
        //_growSlot = new ItemHolder(FlxG.width / 2 - 40, 800);
        //add(_growSlot);
		_treeSegments = new FlxTypedGroup<TreeSegmentSlots>();
		_treeSegments.add(new TreeSegmentSlots([new FlxPoint(200, 770), new FlxPoint(300, 770)]));
		add(_treeSegments);
		_inv = new Inventory();
		add(_inv);
		_draggedItem = null; // not dragging an item to start with
        
        // Start with a goal of 10
        //_growHere = 3;
        //_currentScore = 0;
        
        segNum = 0;
        
        _spawnNewSegment = false;
		
		_dragging = false;
	}
	
	override public function update():Void {
		
        // Handle moving items around
		#if !FLX_NO_MOUSE
		if (FlxG.mouse.justPressed)
		{
			if (_inv.usingMouse())
			{
				_draggedItem = _inv.getClickedItem();
				if (_draggedItem != null)
				{
					add(_draggedItem);
					_dragging = true;
					_dragScroll = false;
					_dragStart = _draggedItem.getScreenXY();
					_mouseOffset = FlxG.mouse.getScreenPosition().subtractPoint(new FlxPoint(_draggedItem.x, _draggedItem.y));
				}
				else
				{
					_inv.switchView();
				}
			}
			else 
			{
				for (segment in _treeSegments)
				{
					if (segment.usingMouse())
					{
						_dragging = true;
						_dragScroll = true;
						_draggedItem = segment.getClickedItem();
						_dragStart = _draggedItem.getScreenXY();
						_mouseOffset = FlxG.mouse.getScreenPosition().subtractPoint(new FlxPoint(_draggedItem.x, _draggedItem.y));
					}
				}
			}
		}
		else if (_dragging && FlxG.mouse.pressed)
		{
			_draggedItem.x = FlxG.mouse.screenX - _mouseOffset.x;
			_draggedItem.y = FlxG.mouse.screenY - _mouseOffset.y;
			if (!_dragScroll)
			{
				_dragScroll = !_draggedItem.overlapsAt(_draggedItem.x, _draggedItem.y + 45, _inv.members[0]);
			}
		}
		else if (_dragging && FlxG.mouse.justReleased)
		{
			_dragging = false;
			_dragScroll = false;
            if (_treeSegments.members.length > 0)
            {
                for (segment in _treeSegments)
                {
                    if (segment.overlapsItem(_draggedItem))
                    {
                        segment.setSlotItem(_draggedItem);
                        _draggedItem = null;
                    }
                }
               /* if (_draggedItem != null && _growSlot.overlaps(_draggedItem, true))
                {
                    _growSlot.setItem(_draggedItem);
                    _draggedItem = null;
                }
                else*/ if (_draggedItem != null)
                {
                    _draggedItem.returnToSource();
                    _draggedItem = null;
                }
            }
            /*else if (_growSlot.overlaps(_draggedItem, true))
            {
                _growSlot.setItem(_draggedItem);
                _draggedItem = null;
            }*/
            else
            {
                _draggedItem.returnToSource();
                _draggedItem = null;
            }
		}
		else {
			if (_inv.usingMouse()) {
				_inv.highlightItem();
			}
		}
		#end
        
        // Handle anything put in the grow slot
        /*if (_growSlot.hasItem())
        {
            _currentScore += _growSlot.heldItemScore();
            _growSlot.consumeItem();
            // Since we increased the score, check if it's time to spawn a new segment
            if (_currentScore >= _growHere)
            {
                _growHere *= 2;
				_treeSegments.clear();
                _treeSegments.add(new TreeSegmentSlots([new FlxPoint(200, 800 - 230 * segNum), new FlxPoint(300, 800 - 230 * segNum)]));
                segNum++;
                _growSlot.y -= 230;
                _spawnNewSegment = true;
                _newSegmentGraphic = AssetPaths.Mix__png;
            }
        }*/
		
        // Check if a combined item should be produced
		for (segment in _treeSegments)
		{
			if (segment.bothFull())
			{
				var potentialCombo:String = segment.combine();
				if (potentialCombo != null)
				{
					_newSegmentGraphic = "assets/images/" + potentialCombo + "Piece.png";
					_inv.addItem(potentialCombo);
					segment.consumeItems();
					_treeSegments.clear();
					if(potentialCombo != "Rocket") {
						_treeSegments.add(new TreeSegmentSlots([new FlxPoint(200, 800 - 209 * segNum), new FlxPoint(300, 800 - 209 * segNum)]));
					}
					segNum++;
					_spawnNewSegment = true;
				}
			}
		}
        
		
    	super.update();
	}
	
	public function usingMouse():Bool
	{
		var needMouse:Bool = false;
		for (segment in _treeSegments)
		{
			if (segment.usingMouse())
			{
				needMouse = true;
			}
		}
		return _inv.usingMouse() || needMouse;
	}
	
	public function scrollScreen():Bool
	{
		return _dragScroll && !_inv.usingMouse();
	}
	
    public function spawnTreeSegment():Bool
    {
        if (_spawnNewSegment)
        {
            _spawnNewSegment = false;
            return true;
        }
        return false;
    }
    
    public function newSegmentGraphic():String
    {
        return _newSegmentGraphic;
    }
}